import uuid
import os
import shutil
import pytz
import json
from datetime import datetime
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa

from ftp_manager import FTPManager
from models import db, User

TEMP_DIR = "/tmp/"

# 创建用户时使用东八区时间
shanghai_tz = pytz.timezone('Asia/Shanghai')

def generate_key_pair():
    # 生成RSA密钥对
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    
    # 序列化私钥
    pem_private = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    )
    
    # 序列化公钥
    pem_public = private_key.public_key().public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    )
    
    return pem_public.decode('utf-8'), pem_private.decode('utf-8')


def create_users(user_name: str, user_id: str, public_key: str, private_key: str, app_version: str, scheme_version: str) -> User:
    new_user = User(
                user_name=user_name,
                uuid=user_id,
                public_key=public_key,
                private_key=private_key,
                is_active=True,
                created_at=datetime.now(shanghai_tz)
            )
    new_user.add_history_entry('创建', f'用户 {new_user.user_name} 已创建')
    db.session.add(new_user)
    db.session.commit()

    # 创建用户目录
    user_dir = TEMP_DIR + new_user.user_name
    if os.path.exists(user_dir):
        shutil.rmtree(user_dir)
    os.makedirs(user_dir, exist_ok=True)
    user_crypto_dir = os.path.join(user_dir, 'crypto')
    os.makedirs(user_crypto_dir, exist_ok=True)

    # 保存用户公钥
    with open(os.path.join(user_crypto_dir, 'public_key.pem'), 'w') as f:
        f.write(new_user.public_key)

    # 保存用户私钥
    with open(os.path.join(user_crypto_dir, 'private_key.pem'), 'w') as f:
        f.write(new_user.private_key)

    # 保存用户UUID
    with open(os.path.join(user_crypto_dir, 'profile'), 'w') as f:
        f.write(new_user.uuid)

    # 保存用户user.profile
    with open(os.path.join(user_crypto_dir, 'user.profile'), 'w') as f:
        json_content = {
                    "user_name": f"{new_user.user_name}",
                    "user_id": f"{new_user.uuid}",
                    "public_key": f"{new_user.public_key}",
                    "app_version": app_version,
                    "scheme_version": scheme_version,
                    "mq":
                        {
                            "user": "dev",
                            "password": "sichip2024",
                            "host": "127.0.0.1",
                            "port": "5672",
                            "queue_name": "operation_queue"
                        },
                    "api_service":
                        {
                            "host": "127.0.0.1",
                            "port": "50051"
                        }
                }

        json.dump(json_content, f, ensure_ascii=False, indent=4)

    # with FTPManager() as ftp_utils:
    #     ftp_utils.remove_userdata(new_user.user_name)
    #     ftp_utils.upload_userdata(new_user.user_name, user_dir)
    # if os.path.exists(user_dir):
    #     shutil.rmtree(user_dir)

    return new_user
